import {sequelize} from '../models'

module.exports = {
  async getPage (opts = {
    tbl: '',
    attrs: [],
    where: [],
    joins: [],
    orders: [],
    ps: 10,
    pn: 1,
    log: false
  }) {

    let seq = sequelize

    let {ps, pn, log} = opts
    let page = {}
    let sql = this.genSql(opts)
    if (log) console.info(sql)
    let rs = await seq.query(sql, {type: seq.QueryTypes.SELECT})

    let countSql = this.countSql(sql)
    if (log) console.info(countSql)
    let cr = await seq.query(countSql, {type: seq.QueryTypes.SELECT})
    let tc = cr[0] && cr[0]['total_count'] ? cr[0]['total_count'] : 0
    let tp = Math.ceil(tc/ps)

    page.pn = pn
    page.ps = ps
    page.tc = tc
    page.rows = rs
    page.tp = tp
    return page
  },
  async getRs (opts = {
    tbl: '',
    attrs: [],
    where: [],
    joins: [],
    orders: [],
    ps: 0,
    pn: 1,
    log: false
  }) {
    let seq = sequelize

    let {log} = opts

    let sql = this.genSql(opts)
    if (log) console.info(sql)
    let rs = await seq.query(sql, {type: seq.QueryTypes.SELECT})
    return rs
  },

  async findAll (opts = {
    tbl: '',
    attrs: [],
    where: [],
    joins: [],
    orders: [],
    ps: 0,
    pn: 1,
    log: false
  }) {
    return await this.getRs(opts)
  },

  async findOne (opts = {
    tbl: '',
    attrs: [],
    where: [],
    joins: [],
    orders: [],
    ps: 1,
    pn: 1,
    log: false
  }) {
    let seq = sequelize
    let {log} = opts
    let sql = this.genSql(opts)
    if (log) console.info(sql)
    let rs = await seq.query(sql, {type: seq.QueryTypes.SELECT})
    if (!rs || !rs[0]) return null
    if (!rs[0]) return null
    return rs[0]
  },

  countSql (sql) {
    sql = sql.replace(/select.*?from/, 'select count(*) as total_count from')
    sql = sql.split(' limit')[0]
    sql = sql.split(' order')[0]
    return sql
  },

  genSql (opts = {
    tbl: '',
    attrs: [],
    where: [],
    joins: [],
    orders: [],
    ps: 0,
    pn: 1
  }) {
    let {tbl, attrs, where, joins, ps, pn, orders} = opts
    let sql = []
    if (!tbl) return ''
    sql.push("select " + attrs.join(',') + " from " + tbl)
    if (joins && joins.length > 0) {
      sql.push(joins.join(' '))
    }
    if (where && where.length > 0) {
      sql.push("where " + where.join(' and '))
    }

    if (orders && orders.length > 0) {
      sql.push("order by " + orders.join(' '))
    }

    if (ps > 0) {
      sql.push("limit " + (pn - 1) * ps + ", " + ps)
    }
    return sql.join(' ')
  }
}
